package com.lhz.utils;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/8/9 20:36
 * @Description:
 **/
@Component
@Slf4j
public class JobLock {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public boolean setLock(String lockKey, String value, long time, TimeUnit timeUnit) {
        return stringRedisTemplate.opsForValue().setIfAbsent(lockKey, value, time, timeUnit);
    }


    public void deleteLock(String lockKey, String value) {

        // 执行脚本 删除锁
        List<String> keyList = Collections.singletonList(lockKey);
        String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> luaScript = RedisScript.of(lua, Long.class);
        Long execute = stringRedisTemplate.execute(luaScript, keyList, value);
        if (execute != 0) {
            log.info("===>>>解锁成功");
        } else {
            log.info("===>>>解锁失败");
        }
    }
}